from http.client import SWITCHING_PROTOCOLS
import random
import datetime
from os import system, name
import time
import threading


# 倒计时线程类
class CountdownThread(threading.Thread):
    def __init__(self, seconds):
        super().__init__()
        self.seconds = seconds
        self.stop_event = threading.Event()
        self.timeout = False

    def run(self):
        while self.seconds > 0 and not self.stop_event.is_set():
            print(f"\n剩余时间：{self.seconds}秒")
            time.sleep(1)
            self.seconds -= 1
        if not self.stop_event.is_set():
            print("时间到！")
            self.stop_event.set()
            self.timeout = True

    def stop(self):
        self.stop_event.set()
        

#玩家类
class Player:
    def __init__(self, name):
        self.name = name#玩家名
        self.current_score = 200#当前分数:随机数是取值1-100，设最大回合数为200
        self.best_score = float('inf')#最好分数
        self.game_history = []#成绩列表

#猜数字游戏类GuessNumberGame()
class GuessNumberGame:
    #初始化
    def __init__(self):
        self.target_number = 0 #初始化随机目标数字=0
        self.start_time = None
        self.end_time = None
        self.players = {}
    #生成随机目标数字
    def generate_target_number(self):#生成一个随机目标数字
        self.target_number = random.randint(1, 100)#数字范围1-100

    #游戏初始化
    def start_game(self, player_name):

        #判断玩家对象是否存在于记录
        player = self.players.get(player_name)
        if not player:
            player = Player(player_name)
            self.players[player_name] = player 
        
        #开始游戏的初始化操作
        player.current_score = 0
        self.generate_target_number()
        self.start_time = datetime.datetime.now()
        print(f"游戏开始！目标数字已生成，请在规定时间内猜出该数字。")

    #玩家的猜测操作
    def make_guess(self, player_name, guess):
        #判断玩家对象是否存在于记录
        player = self.players.get(player_name)
        if not player:
            print("请先开始游戏！")
            return
        #操作判断
        #while True:
        player.current_score += 1#分数/回合数+1
        if guess == self.target_number:#guess:玩家猜测的数字，self.target_number：随机数
            self.end_time = datetime.datetime.now()
            elapsed_time = self.end_time - self.start_time
            self.clear()#清屏操作
            print(f"恭喜！你猜对了！用时：{elapsed_time.total_seconds()}秒")
            #最佳成绩判断
            if player.current_score < player.best_score:
                player.best_score = player.current_score
            #游戏记录信息的字典
            game_record = {
                'date': datetime.datetime.now().strftime("%Y-%m-%d"),
                'time': datetime.datetime.now().strftime("%H:%M:%S"),
                'score': player.current_score
            }
            player.game_history.append(game_record)
            self.print_game_history(player_name)
            return 1
            #break
        elif guess < self.target_number:
            self.clear()#清屏操作
            print("猜的数字太小了！")
            return 0
        else:
            self.clear()#清屏操作
            print("猜的数字太大了！")
            return 0
    #打印玩家的游戏历史记录
    def print_game_history(self, player_name):
        player = self.players.get(player_name)
        print(f"{player.name}的游戏记录：")
        for record in player.game_history:
            print(f"日期：{record['date']}，时间：{record['time']}，成绩：{record['score']}")
        print(f"当前成绩：{player.current_score}，最好成绩：{player.best_score}")
        self.save_game_history(player_name)  # 保存游戏记录到文件
    #清屏操作
    def clear(self):
    # for windows
        if name == 'nt':
            _ = system('cls')

        # for mac and linux(here, os.name is 'posix')
        else:
            _ = system('clear')
    # 保存游戏记录到文件
    def save_game_history(self, player_name):
        player = self.players.get(player_name)
        if player:
            with open('his.txt', 'a') as file:
                file.write(f"玩家名: {player.name}\n")
                file.write(f"最佳成绩: {player.best_score}\n")
                file.write(f"游玩时间: {datetime.datetime.now()}\n")
                file.write("-----------------\n")
    #打印文件
    def read_game_history(self):
        with open('his.txt', 'r') as file:
            history = file.read()
            print(history)
        return history
    #菜单
    def menu_show(self):
        print('-------猜数字~~~~~~~~----------')
        print('------------------------------')
        print('---------1.开始游戏------------')
        print('---------2.记录展示------------')
        print('---------3.规则说明------------')
        print('---------0.退出----------------')
        print('------------------------------')
        #规则
    def rule_show(self):
        print('---------规则--------------------')
        print('---------------------------------')
        print('1.猜数字，数字猜对者获胜-----------')
        print('2.成绩为猜数字所需回合，回合少为最佳')
        print('3.每回合有15秒倒计时，超时本回合无效，\n该回合为惩罚回合计入回合数')
        print('祝君游戏愉快----------------------')
        print('------------------------------')
    def game(self,player_name):
        self.clear()
        #游戏输入判断逻辑
        while True:
            countdown_thread = CountdownThread(15)  # 创建倒计时线程
            countdown_thread.start()  # 启动倒计时线程
            guess = input("请输入你猜测的数字（1-100）：\n")
            countdown_thread.stop()  # 停止倒计时线程

            if countdown_thread.timeout:#判断倒计时进程是否停止
                self.clear()
                print("超时，请重新输入一个数字！")
                continue
            else:#游戏判断逻辑
                if guess.isdigit():
                    guess = int(guess)
                    if self.make_guess(player_name, guess)==1:
                        break
                    else:
                        continue
                        
                else:
                    self.clear()
                    print("输入无效，请输入一个数字！")
                    continue
        #游戏结束
        play_again = input("是否再次玩游戏？(Y/N)：")
        if play_again.upper() == 'Y':
            self.game(player_name)
        self.clear()
    
    #游戏函数
    def play_game(self):
        print('------猜数字~~~~~--------\n\n')
        player_name = input("请输入玩家姓名：")
        self.start_game(player_name)
        self.clear()#清屏操作
        self.menu_show()
        #选项判断：
        while True:
            choose=input("请输入选项对应的数字")
            if choose==("1"):
                self.game(player_name)
                break
            elif choose==("2"):
                #self.print_game_history(player_name)#打印信息
                self.read_game_history()
                continue
            elif choose==("3"):
                self.rule_show()
                continue
            elif choose==("0"):
                self.clear()#清屏操作
                break
            else:
                print("打错了，重来")

#主代码
game = GuessNumberGame()
game.play_game()